home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 6446 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.7 KB

  1. Path: rcp6.elan.af.mil!rscernix!danpop
  2. From: danpop@mail.cern.ch (Dan Pop)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: HELP: Illegal Pointer Arithmetic
  5. Date: 24 Feb 96 00:18:59 GMT
  6. Organization: CERN European Lab for Particle Physics
  7. Message-ID: <danpop.825121139@rscernix>
  8. References: <4gj0ug$730@news.one.net>
  9. NNTP-Posting-Host: ues5.cern.ch
  10. X-Newsreader: NN version 6.5.0 #7 (NOV)
  11.  
  12. In <4gj0ug$730@news.one.net> Oren Levin <oren@one.net> writes:
  13.  
  14. >        while (! feof (fin))
  15.                 ^^^^^^^^^^^^^^^^^^^^     
  16. Are there any books teaching this idiocy or is it only Pascal-induced
  17. brain damage?  (See the FAQ.)
  18.  
  19. >        {
  20. >            /* read a record */
  21. >            if (fgets (buffer, 127, fin) == NULL)
  22. >                break;
  23. >            
  24. >            /* get rid of the trailing carrage return */
  25. >            buffer [strlen (buffer) - 1] = "\0";
  26.                                                        ^^^^
  27. This is not an integral type that can be assigned to a char.  Use either
  28. 0 or '\0' (apart from the visual aspect, they're one and the same thing).
  29. (OTOH, "\0" is a string literal containing two null characters.  In a
  30. value context, it decays into a pointer to char and cannot be assigned
  31. to a character.) 
  32.  
  33. However, the code is unsafe, unless it is guaranteed that no line from
  34. the fin stream can possibly be longer than 126 characters (including the
  35. newline).  If the line is longer, this code simply destroys the last
  36. character read from the stream.  A safer approach would be:
  37.  
  38.     if ((p = strchr(buffer, '\n')) != NULL) *p = '\0';
  39.  
  40. For some reason I like this better than:
  41.  
  42.     last = strlen(buffer) - 1;
  43.     if (buffer[last] == '\n') buffer[last] = '\0';
  44.  
  45. Dan
  46. --
  47. Dan Pop
  48. CERN, CN Division
  49. Email: danpop@mail.cern.ch 
  50. Mail:  CERN - PPE, Bat. 31 R-004, CH-1211 Geneve 23, Switzerland
  51.